package com.drinkdelivery.web.controller;



import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.drinkdelivery.common.config.RuoYiConfig;
import com.drinkdelivery.common.core.domain.AjaxResult;
import com.drinkdelivery.common.utils.file.FileUploadUtils;
import com.drinkdelivery.common.domain.SliderImage;
import com.drinkdelivery.common.request.SliderImageRequest;
import com.drinkdelivery.common.utils.file.FileUtils;
import com.drinkdelivery.service.ISliderImageService;

import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import cn.hutool.core.util.IdUtil;
/**
 *轮播图Controller
 *
 *
 */
@Api(tags = "轮播图")
@RestController
@RequestMapping("/admin/sliderImage")
public class SliderImageController {

    @Autowired
    private ISliderImageService sliderImageService;
    @PostMapping("/upload")
    public AjaxResult upload(@RequestParam("multipartFile") MultipartFile multipartFile)throws IOException {
        String filePath = RuoYiConfig.getUploadPath();
        // 上传并返回新文件名称
        String url = FileUploadUtils.upload(filePath, multipartFile);
        String fileName = multipartFile.getOriginalFilename();
        String name = fileName.split("\\.")[0];
//        String url = serverConfig.getUrl() + fileName;
        String type = fileName.split("\\.")[1];
        long size = multipartFile.getSize();

        Map<String, Object> map = new HashMap<>();
        map.put("name",name);
        map.put("type",type);
        map.put("size",size);
        map.put("url",url);
        return AjaxResult.success("发送成功",map);
    }


    @PostMapping("/insert")
    public AjaxResult insert(@RequestBody SliderImage sliderImage){
//        // 自定义的workerId和datacenterId
//        long workerId = 1;
//        long datacenterId = 1;
//        long id = IdUtil.createSnowflake(workerId,datacenterId).nextId();
//        sliderImage.setId(id);
//        //查询出轮播图列表
//        List<SliderImage> sliderImageList = sliderImageService.getList();
//        //提取sort
//        List<Integer> sortList = sliderImageList.stream().map(SliderImage::getSort).collect(Collectors.toList());
//        //把数字最大sort拿出来，然后进行+1，最后赋值给新的轮播图sort
//        Integer sort = sortList.get(sortList.size() - 1 );
//        sliderImage.setSort(sort + 1);
//        if(sliderImageService.save(sliderImage)){
//            return AjaxResult.success("新增成功");
//        }else {
//            String profile = RuoYiConfig.getProfile();
//            String absPath = sliderImage.getImageUrl().replace("/profile",profile);
//            File file = new File(absPath);
//            file.delete();
//            return AjaxResult.success("新增失败,且图片取消上传");
//        }
//        // 声明变量以便后续使用
//        String profile = null;
//        String absPath = null;
//        File file = null;

        // 自定义的workerId和datacenterId
        long workerId = 1;
        long datacenterId = 1;
        try {
            if (ObjectUtil.isNull(sliderImage.getImageUrl()))
                return AjaxResult.error("url为空");
            //获取商户id
            // todo
//            Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
//            先写死
            sliderImage.setMerchantId(1);
            //生成雪花id
            long id = IdUtil.createSnowflake(workerId, datacenterId).nextId();
            sliderImage.setId(id);
            // 查询出轮播图列表
            List<SliderImage> sliderImageList = sliderImageService.getList();
            // 提取 sort
            List<Integer> sortList = sliderImageList.stream().map(SliderImage::getSort).collect(Collectors.toList());
            // 把数字最大 sort 拿出来，然后进行 +1，最后赋值给新的轮播图 sort
            Integer sort = sortList.get(sortList.size() - 1);
            sliderImage.setSort(sort + 1);

            // 执行保存操作
            if (sliderImageService.save(sliderImage)) {
                return AjaxResult.success("新增成功");
            } else {
                // 如果保存失败，执行图片删除逻辑
                throw new RuntimeException("新增失败");  // 手动抛出异常模拟失败情景
            }
        } catch (RuntimeException e) {
            //处理异常，并记录失败信息
//            if (sliderImage.getImageUrl() != null && !sliderImage.getImageUrl().isEmpty()) {
//                try {
//                    profile = RuoYiConfig.getProfile();
//                    absPath = sliderImage.getImageUrl().replace("/profile", profile);
//                    file = new File(absPath);
//                    if (file.exists()) {
//                        file.delete();  // 删除文件
//                    }
//                } catch (Exception deleteException) {
//                    // 删除失败的日志记录，避免影响主要操作
//                    System.err.println("图片删除失败：" + deleteException.getMessage());
//                }
//            }
            FileUtils.deleteFileIfExists(sliderImage.getImageUrl());
            System.err.println("新增失败"+e);
            throw  new RuntimeException(e.getMessage());
        }

    }
    @PostMapping("/update")
    public AjaxResult update(@RequestBody SliderImage sliderImage){

        try {
            if (sliderImageService.updateById(sliderImage)) {
                return AjaxResult.success("修改成功");
            } else {
                // 如果保存失败，执行图片删除逻辑
                throw new RuntimeException("修改失败");
            }
        } catch (RuntimeException e) {
            FileUtils.deleteFileIfExists(sliderImage.getImageUrl());
            System.err.println("修改失败"+e);
            throw  new RuntimeException(e.getMessage());
        }

    }


    @PostMapping("/cancelUpload")
    public AjaxResult cancelUpload(@RequestParam String url){
        String profile = RuoYiConfig.getProfile();
        //将url替换成本地路径
        String absPath = url.replace("/profile", profile);

        File file = new File(absPath);
        if (FileUtils.deleteFile(absPath)) {
//            file.delete();  // 删除文件
            return AjaxResult.success("图片上传取消", absPath);
        }else {
            return AjaxResult.error("图片上传取消失败，没有该图片", absPath);
        }
    }

    @GetMapping("/getById")
    public AjaxResult getOne(@RequestParam  Long id){

      SliderImage sliderImage = sliderImageService.getById(id);

        return AjaxResult.success("发送成功",sliderImage);
    }

    @DeleteMapping("/delById")
    public AjaxResult delById(@RequestParam  Long id){
        LambdaUpdateWrapper<SliderImage> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(SliderImage::getId,id);
        lambdaUpdateWrapper.set(SliderImage::getIsDeleted,1);

        if (sliderImageService.update(lambdaUpdateWrapper)){
            LambdaQueryWrapper<SliderImage> lqw = new LambdaQueryWrapper<>();
            lqw.select(SliderImage::getImageUrl);
            lqw.eq(SliderImage::getId,id);
            lqw.last("limit 1");
            SliderImage sliderImage = sliderImageService.getOne(lqw);
            FileUtils.deleteFileIfExists(sliderImage.getImageUrl());
        }

        return AjaxResult.success("删除成功");
    }

    @GetMapping("/getList")
    public AjaxResult getList(){

        //先写死,商户id
        Long userId = 1L;

        List<SliderImage> sliderImageList = new ArrayList<>();
//
//        LambdaQueryWrapper<SliderImage> lqw = new LambdaQueryWrapper<>();
//        lqw.eq(SliderImage::getIsDeleted,0);
//        lqw.orderByAsc(SliderImage::getSort);
//        lqw.eq(SliderImage::getMerchantId,userId);
////        sliderImageList = sliderImageService.list(lqw);
        sliderImageList = sliderImageService.getList();
        return AjaxResult.success("发送成功",sliderImageList);
    }

    @PostMapping("/saveList")
    public AjaxResult saveList( @RequestBody SliderImageRequest sliderImageRequest){

        List<SliderImage> sliderImageList = sliderImageRequest.getSliderImageList();
        //提取sort，从小到大排序
        List<Integer> sortList = sliderImageList.stream().map(SliderImage::getSort).sorted().collect(Collectors.toList());

        //把sort从小到大赋值给轮播图列表
        Integer n = 0;
        for (SliderImage sliderImage:sliderImageList){
            sliderImage.setSort(sortList.get(n));
            n++;
        }

        sliderImageService.updateBatchById(sliderImageList);

        return AjaxResult.success("发送成功");
    }


}
